package com.apps.realtyportal;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import mapviewballoons.example.custom.CustomItemizedOverlay;
import mapviewballoons.example.custom.CustomOverlayItem;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.app.SherlockListFragment;
import com.apps.essentials.AlertDialogManager;
import com.apps.essentials.ConsumeWebService;
import com.apps.realtyportal.HomeActivity.Exchanger;
import com.apps.realtyportal.PriceFragment.MapFragment;
import com.apps.realtyportal.PriceFragment.MyListFragment;
import com.apps.routing.Route;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

public class TypeFragment extends SherlockListFragment {

	private MapFragment mMapFragment;
	private MyListFragment mMyListFragment;
	private Fragment mVisible = null;
	/** An array of items to display in ArrayList */
	String list_of_types[] = new String[] { 
			"Codominium",
			"Building",
			"Subdivision",
			"House",
			"Office"};
	//start here
	List<Overlay> newmapOverlays;
	ConsumeWebService cws;
	String centerAddress = "Cebu City";
    SherlockFragmentActivity fa;
	private ActionBar actionbar;
	private MapController controlmap;
	AlertDialogManager alert = new AlertDialogManager();
	public final ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
	Context appContext;
	HashMap<String, String> map;
	CustomItemizedOverlay<CustomOverlayItem> newitemizedOverlay2;
	String selectedType;
	GeoPoint gp;
	Drawable drawable;
	public static final String KEY_ID = "property_id";
	public static final String KEY_NAME = "property_name";
	public static final String KEY_DESCRIPTION = "property_description";
	public static final String KEY_PRICE = "price";
	public static final String KEY_LATITUDE = "latitude";
	public static final String KEY_LONGITUDE = "longitude";
	public static final String KEY_ADDRESS = "address";
	public static final String KEY_TYPE = "type";
	public static final String KEY_IMAGE = "main_image";
	public static final String KEY_PERSONFNAME="firstname";
	public static final String KEY_PERSONLNAME="lastname";
	public static final String KEY_PERSONCONTACT="mobile";
	int minLat = Integer.MAX_VALUE;
	int minLong = Integer.MAX_VALUE;
	int maxLat = Integer.MIN_VALUE;
	int maxLong = Integer.MIN_VALUE;	
	CustomOverlayItem overlayItem3;
	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {

	}

	public void onRestoreInstanceState(Bundle savedInstanceState) {

	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		// super.onListItemClick(l, v, position, id);
		Toast.makeText(getSherlockActivity(), "position" + position,
				Toast.LENGTH_SHORT).show();

		Activity activity = getActivity();
		newmapOverlays = HomeActivity.Exchanger.mMapView.getOverlays();
		newmapOverlays.clear();
		HomeActivity.Exchanger.mMapView.setBuiltInZoomControls(true);
		controlmap = HomeActivity.Exchanger.mMapView.getController();
		selectedType = list_of_types[position].toLowerCase().toString();
		cws = new ConsumeWebService();
		final String data = cws.getAllProperty();
   		
		// final ViewGroup parent = (ViewGroup) HomeActivity.Exchanger.mMapView
		// .getParent();
		// if (parent != null)
		// parent.removeView(HomeActivity.Exchanger.mMapView);
		
		if (activity != null) {

			Log.i("tae", "poop");
			// Fragments have access to their parent Activity's FragmentManager.
			// You can
			// obtain the FragmentManager like this.
			FragmentManager fm = getFragmentManager();
			
//			AsyncTask newtask = new AsyncTask(){
//			    public ProgressDialog dialog=new ProgressDialog(fa);
//			    Route route;
//				@Override
//				
//				protected void onPreExecute() {
//		            this.dialog.setMessage("Loading data...");
//		            this.dialog.show();
//				};
//				protected Object doInBackground(Object... params) {
//					// TODO Auto-generated method stub
//					try{
//						JSONArray array = new JSONArray(data);
//						
//						for (int i = 0; i < array.length(); i++) {
//							map = new HashMap<String, String>();
//							
//							JSONObject e = array.getJSONObject(i);
//							map.put("property_id", e.getString(KEY_ID));
//							map.put("property_name", e.getString(KEY_NAME));
//							map.put("property_description", e.getString(KEY_DESCRIPTION));
//							map.put("price", e.getString(KEY_PRICE));
//							map.put("latitude", e.getString(KEY_LATITUDE));
//							map.put("longitude", e.getString(KEY_LONGITUDE));
//							map.put("address", e.getString(KEY_ADDRESS));
//							map.put("type", e.getString(KEY_TYPE));
//							map.put("image", e.getString(KEY_IMAGE));
//							map.put("firstname", e.getString("firstname"));
//							map.put("lastname", e.getString("lastname"));
//							map.put("mobile", e.getString("mobile"));
//							map.put("email", e.getString("email_address"));
//												
//							mylist.add(map);
//						}
//					}catch(Exception e){
//						//Log.e("error",e.getMessage());
//					}
//					return null;
//				
//				}
//				
//				@Override
//				protected void onPostExecute(Object result) {
//					// TODO Auto-generated method stub
//					// TODO Auto-generated method stubsi
//					newmapOverlays = Exchanger.mMapView.getOverlays();
//			    	if (this.dialog!=null) {
//			            this.dialog.dismiss();	            
//			        }	    	 
//			    	Toast.makeText(fa, ""+mylist, Toast.LENGTH_LONG).show();
////			    	if(!mylist.isEmpty()){
////			    	
////					    	for(int i = 0; i<mylist.size(); i++){
////					    		HashMap<String, String> map = mylist.get(i); 		
////					    		String tr1 = (String) map.get(KEY_LATITUDE);
////					    		String tr2 = (String) map.get(KEY_LONGITUDE);
////								String pname = map.get(KEY_NAME);
////								String pdescription = map.get(KEY_DESCRIPTION);
////								String paddress = map.get(KEY_ADDRESS);
////								String pimage = map.get(KEY_IMAGE);
////								String ptype = map.get(KEY_TYPE);
////								String pprice = map.get(KEY_PRICE);
////								String pindex = map.get(KEY_ID).toString();
////								String pagent = map.get("firstname");
////								if(selectedType.equals(ptype)){
////					    			int lat1 = Integer.valueOf((String) tr1);
////					    			int  long2= Integer.valueOf((String) tr2);
//////					    			double cinttr1 = (double) lat1/1E6;
//////					    			double cinttr2 = (double) long2/1E6;
////
////									gp = new GeoPoint(lat1, long2);
////									minLat  = (int) Math.min( gp.getLatitudeE6(), minLat );
////								    minLong = (int) Math.min( gp.getLongitudeE6(), minLong);
////								    maxLat  = (int) Math.max( gp.getLatitudeE6(), maxLat );
////								    maxLong = (int) Math.max( gp.getLongitudeE6(), maxLong );
////									if(ptype.equalsIgnoreCase("building")){
////										drawable = getResources().getDrawable(R.drawable.building2);
////									}else if(ptype.equalsIgnoreCase("house")){
////										drawable = getResources().getDrawable(R.drawable.house2);
////									}else if(ptype.equalsIgnoreCase("subdivision")){
////										drawable = getResources().getDrawable(R.drawable.subdivision2);
////									}else if(ptype.equalsIgnoreCase("condominium")){
////										drawable = getResources().getDrawable(R.drawable.building2);
////									}
////								    
//////							    	drawable = getResources().getDrawable(R.drawable.building2);
////							    	newitemizedOverlay2 = new CustomItemizedOverlay<CustomOverlayItem>(drawable, Exchanger.mMapView);
////									  overlayItem3 = new CustomOverlayItem(gp, ""+pname, 
////												"Description: "+pdescription,"Address: "+paddress,pindex,pprice,ptype,pagent,
////												pimage);
////												newitemizedOverlay2.addOverlay(overlayItem3);
////												newmapOverlays.add(newitemizedOverlay2);
////												newitemizedOverlay2.populateNow();	
//////					    			Toast.makeText(getApplicationContext(), "Converted int lat "+lat1+"Converted int lon "+long2, Toast.LENGTH_LONG).show();
//////					    			Toast.makeText(getApplicationContext(), "Converted double lat "+cinttr1+"Converted double lon "+cinttr2, Toast.LENGTH_LONG).show();
////					    			
////					    		}
//////					    		Toast.makeText(getApplicationContext(), "data lat "+tr1+" data lon "+tr2, Toast.LENGTH_LONG).show();
////					    	}
////									
////					
////			    	}else if(mylist.isEmpty()){
////			    		alert.showAlertDialog(fa, "NO DATA FOUND",
////								"Sorry no data found. Try to check connection",
////								false);	    		
////			    	}
////					controlmap.zoomToSpan(Math.abs( minLat - maxLat ), Math.abs( minLong - maxLong ));
////					controlmap.animateTo(new GeoPoint((maxLat + minLat)/2, (maxLong + minLong)/2 ));
////					Exchanger.mMapView.invalidate();
//				}
//			};
//			newtask.execute();
			try {

				JSONArray array = new JSONArray(data);
				
				for (int i = 0; i < array.length(); i++) {
					map = new HashMap<String, String>();
					
					JSONObject e = array.getJSONObject(i);
					map.put("property_id", e.getString(KEY_ID));
					map.put("property_name", e.getString(KEY_NAME));
					map.put("property_description", e.getString(KEY_DESCRIPTION));
					map.put("price", e.getString(KEY_PRICE));
					map.put("latitude", e.getString(KEY_LATITUDE));
					map.put("longitude", e.getString(KEY_LONGITUDE));
					map.put("address", e.getString(KEY_ADDRESS));
					map.put("type", e.getString(KEY_TYPE));
					map.put("image", e.getString(KEY_IMAGE));
					map.put("firstname", e.getString("firstname"));
					map.put("lastname", e.getString("lastname"));
					map.put("mobile", e.getString("mobile"));
					map.put("email", e.getString("email_address"));
										
					mylist.add(map);
				
				}
			} catch (JSONException e) {
				Log.e("log_tag", "Error parsing data " + e.toString());
			}
			

			for(int i = 0; i<mylist.size(); i++){
	    		HashMap<String, String> map = mylist.get(i); 		
	    		String tr1 = (String) map.get(KEY_LATITUDE);
	    		String tr2 = (String) map.get(KEY_LONGITUDE);
				String pname = map.get(KEY_NAME);
				String pdescription = map.get(KEY_DESCRIPTION);
				String paddress = map.get(KEY_ADDRESS);
				String pimage = map.get(KEY_IMAGE);
				String ptype = map.get(KEY_TYPE);
				String pprice = map.get(KEY_PRICE);
				String pindex = map.get(KEY_ID).toString();
				String pagent = map.get("firstname");
				String pcontact = map.get("mobile");
			if(selectedType.equals(ptype.toString())){
				Toast.makeText(getSherlockActivity(), ""+mylist, Toast.LENGTH_LONG).show();
    			int lat1 = Integer.valueOf((String) tr1).intValue();
    			int  long2= Integer.valueOf((String) tr2).intValue();
//    			double cinttr1 = (double) lat1/1E6;
//    			double cinttr2 = (double) long2/1E6;

				gp = new GeoPoint(lat1, long2);
				minLat  = (int) Math.min( gp.getLatitudeE6(), minLat );
			    minLong = (int) Math.min( gp.getLongitudeE6(), minLong);
			    maxLat  = (int) Math.max( gp.getLatitudeE6(), maxLat );
			    maxLong = (int) Math.max( gp.getLongitudeE6(), maxLong );
				if(ptype.equalsIgnoreCase("building")){
					drawable = getResources().getDrawable(R.drawable.building2);
				}else if(ptype.equalsIgnoreCase("house")){
					drawable = getResources().getDrawable(R.drawable.house2);
				}else if(ptype.equalsIgnoreCase("subdivision")){
					drawable = getResources().getDrawable(R.drawable.subdivision2);
				}else if(ptype.equalsIgnoreCase("condominium")){
					drawable = getResources().getDrawable(R.drawable.building2);
				}
			    
//		    	drawable = getResources().getDrawable(R.drawable.building2);
		    	newitemizedOverlay2 = new CustomItemizedOverlay<CustomOverlayItem>(drawable, Exchanger.mMapView);
				  overlayItem3 = new CustomOverlayItem(gp, ""+pname, 
							"Description: "+pdescription,"Address: "+paddress,pindex,pprice,ptype,pagent,pcontact,
							pimage);
							newitemizedOverlay2.addOverlay(overlayItem3);
							newmapOverlays.add(newitemizedOverlay2);
							newitemizedOverlay2.populateNow();	
//    			Toast.makeText(getApplicationContext(), "Converted int lat "+lat1+"Converted int lon "+long2, Toast.LENGTH_LONG).show();
//    			Toast.makeText(getApplicationContext(), "Converted double lat "+cinttr1+"Converted double lon "+cinttr2, Toast.LENGTH_LONG).show();
//							controlmap.zoomToSpan(Math.abs( minLat - maxLat ), Math.abs( minLong - maxLong ));
//							controlmap.animateTo(new GeoPoint((maxLat + minLat)/2, (maxLong + minLong)/2 ));
//							Exchanger.mMapView.invalidate();
	}
}
			if (fm != null) {


				
				Fragment productDetailFragment = new MapFragment();
				FragmentTransaction transaction = getFragmentManager()
						.beginTransaction();
				transaction.addToBackStack(null);
				transaction
						.replace(android.R.id.content, productDetailFragment)
						.commit();
			}

			// Display a simple Toast to demonstrate that the click event is
			// working. Notice that Fragments have a
			// getString() method just like an Activity, so that you can quickly
			// access your localizSed Strings.
//			controlmap.zoomToSpan(Math.abs( minLat - maxLat ), Math.abs( minLong - maxLong ));
//			controlmap.animateTo(new GeoPoint((maxLat + minLat)/2, (maxLong + minLong)/2 ));
//			HomeActivity.Exchanger.mMapView.invalidate();
//			Toast.makeText(activity, "Pooop" + "  " + "tae", Toast.LENGTH_SHORT)
//					.show();									
//					listoflat.clear();
//					listoflon.clear();
//					pname.clear();
//					pdescription.clear();
//					pprice.clear();
//					arptype.clear();
//
//		}
			
			controlmap.zoomToSpan(Math.abs( minLat - maxLat ), Math.abs( minLong - maxLong ));
			controlmap.animateTo(new GeoPoint((maxLat + minLat)/2, (maxLong + minLong)/2 ));
			HomeActivity.Exchanger.mMapView.invalidate();
		}
	}
	
	public void geoCodeLocation(){
		
		
	}

	// @Override
	// public void onCreate(Bundle savedInstanceState) {
	// requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
	// // This has to be called before setContentView and you must use the
	// // class in com.actionbarsherlock.view and NOT android.view
	// requestWindowFeature(Window.FEATURE_PROGRESS);
	// super.onCreate(savedInstanceState);
	// setContentView(R.layout.main);
	//
	// // We instantiate the MapView here, it's really important!
	// Exchanger.mMapView = new MapView(this,
	// "0P9evGBeKSCPTOeo6QNz-E9sdRKSgNFXBW0kv1Q"); // TODO: Replace for
	// // API Key!
	//
	// setupFragments();
	// // We manually show the list Fragment.d
	// showFragment(mMyListFragment);
	//
	// }
	
	public void loadWebService(){
		cws = new ConsumeWebService();
		 String data = cws.getAllProperty();
		 
		 try {

				JSONArray array = new JSONArray(data);
				
				for (int i = 0; i < array.length(); i++) {
					map = new HashMap<String, String>();
					
					JSONObject e = array.getJSONObject(i);
					map.put("property_id", e.getString(KEY_ID));
					map.put("property_name", e.getString(KEY_NAME));
					map.put("property_description", e.getString(KEY_DESCRIPTION));
					map.put("price", e.getString(KEY_PRICE));
					map.put("latitude", e.getString(KEY_LATITUDE));
					map.put("longitude", e.getString(KEY_LONGITUDE));
					map.put("address", e.getString(KEY_ADDRESS));
					map.put("type", e.getString(KEY_TYPE));
					map.put("image", e.getString(KEY_IMAGE));
					map.put("firstname", e.getString("firstname"));
					map.put("lastname", e.getString("lastname"));
					map.put("mobile", e.getString("mobile"));
					map.put("email", e.getString("email_address"));
										
					mylist.add(map);

				}
			} catch (JSONException e) {
				Log.e("log_tag", "Error parsing data " + e.toString()+"diri jud");
			}finally{
				
			}
	//	 Toast.makeText(getApplicationContext(), ""+mylist, Toast.LENGTH_LONG).show();		
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// View view = inflater.inflate(R.layout.try_main, container, false);
		// ** Creating array adapter to set data in listview */
		// requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);

		/** Creating array adapter to set data in listview */
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity()
				.getBaseContext(), android.R.layout.simple_list_item_1,
				list_of_types);
		fa = (SherlockFragmentActivity)super.getActivity();
		/** Setting the array adapter to the listview */
		setListAdapter(adapter);

		return super.onCreateView(inflater, container, savedInstanceState);

		/**
		 * This has to be called before setContentView and you must use the
		 * //class in com.actionbarsherlock.view and NOT android.view
		 * //requestWindowFeature(Window.FEATURE_PROGRESS);
		 * super.onCreate(savedInstanceState); View view =
		 * inflater.inflate(R.layout.main, container);
		 */
		/** Setting the array adapter to the listview */

	}

	@Override
	public void onStart() {
		super.onStart();
		// HomeActivity h = new HomeActivity();
		// actionbar = h.getSupportActionBar();
		// actionbar.setDisplayHomeAsUpEnabled(true);
		/** Setting the multiselect choice mode for the listview */
		getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);

	}

	/**
	 * This method does the setting up of the Fragments. It basically checks if
	 * the fragments exist and if they do, we'll hide them. If the fragments
	 * don't exist, we create them, add them to the FragmentManager and hide
	 * them.
	 */
	// private void setupFragments() {
	// final FragmentTransaction ft = getSupportFragmentManager()
	// .beginTransaction();
	//
	// /*
	// * If the activity is killed while in BG, it's possible that the
	// * fragment still remains in the FragmentManager, so, we don't need to
	// * add it again.
	// */
	// mMapFragment = (MapFragment) getSupportFragmentManager()
	// .findFragmentByTag(MapFragment.TAG);
	// if (mMapFragment == null) {
	// mMapFragment = new MapFragment();
	// ft.add(R.id.fragment_container, mMapFragment, MapFragment.TAG);
	// }
	// ft.hide(mMapFragment);
	//
	// mMyListFragment = (MyListFragment) getSupportFragmentManager()
	// .findFragmentByTag(MyListFragment.TAG);
	// if (mMyListFragment == null) {
	// mMyListFragment = new MyListFragment();
	// ft.add(R.id.fragment_container, mMyListFragment, MyListFragment.TAG);
	// }
	// ft.hide(mMyListFragment);
	//
	// ft.commit();
	// }

	/**
	 * This method shows the given Fragment and if there was another visible
	 * fragment, it gets hidden. We can just do this because we know that both
	 * the mMyListFragment and the mMapFragment were added in the Activity's
	 * onCreate, so we just create the fragments once at first and not every
	 * time. This will avoid facing some problems with the MapView.
	 * 
	 * @param fragmentIn
	 *            The fragment to show.
	 */
	// private void showFragment(Fragment fragmentIn) {
	// if (fragmentIn == null)
	// return;
	//
	// final FragmentTransaction ft = getSupportFragmentManager()
	// .beginTransaction();
	// ft.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
	//
	// if (mVisible != null)
	// ft.hide(mVisible);
	//
	// ft.show(fragmentIn).commit();
	// mVisible = fragmentIn;
	// }

	/**
	 * This class acts as an exchanger between the Activity and the MapFragment,
	 * so if you want, you can put the MapFragment class in a separate java
	 * file.
	 * 
	 * @author Xavi
	 * 
	 */
	public static class Exchanger {
		// We will use this MapView always.
		public static MapView mMapView;
	}

	/**
	 * This is our ListFragment class. You can put it in a separate java file.
	 * 
	 * @author Xavi
	 * 
	 */
	public static class MyListFragment extends SherlockListFragment {

		public static final String TAG = "listFragment";

		private final String[] mItems = { "List Item 1", "List Item 2",
				"List Item 3", "List Item 4", "List Item 5", "List Item 6",
				"List Item 7", "List Item 8", "List Item 9", "List Item 10" };

		public MyListFragment() {
		}

		@Override
		public void onCreate(Bundle arg0) {
			super.onCreate(arg0);
			setRetainInstance(true);
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup vg,
				Bundle data) {
			// Inflate the ListView layout file.
			return inflater.inflate(R.layout.list_fragment, null);
		}

		@Override
		public void onViewCreated(View arg0, Bundle arg1) {
			super.onViewCreated(arg0, arg1);
			setListAdapter(new ArrayAdapter<String>(getSherlockActivity(),
					android.R.layout.simple_list_item_1, android.R.id.text1,
					mItems));
		}
	}

	/**
	 * This is the Fragment class that will hold the MapView as its content
	 * view. You can put it in a separate java file.
	 * 
	 * @author Xavi
	 * 
	 */
	public static class MapFragment extends SherlockFragment {

		public static final String TAG = "mapFragment";

		public MapFragment() {
		}

		@Override
		public void onCreate(Bundle arg0) {
			super.onCreate(arg0);
			setRetainInstance(true);
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup vg,
				Bundle data) {
			// The Activity created the MapView for us, so we can do some init
			// stuff.
			// View v = inflater.inflate(R.layout.main, vg, false);

			final ViewGroup parent = (ViewGroup) HomeActivity.Exchanger.mMapView
					.getParent();

			if (parent != null)
				parent.removeView(HomeActivity.Exchanger.mMapView);

			HomeActivity.Exchanger.mMapView.setClickable(true);
			

			/*
			 * If you're getting Exceptions saying that the MapView already has
			 * a parent, uncomment the next lines of code, but I think that it
			 * won't be necessary. In other cases it was, but in this case I
			 * don't this should happen.
			 */
			/*
			 * final ViewGroup parent = (ViewGroup)
			 * Exchanger.mMapView.getParent(); if (parent != null)
			 * parent.removeView(Exchanger.mMapView);
			 */

			return HomeActivity.Exchanger.mMapView;
		}
	}

}